<?php

class UsersController extends AppController {

    var $name = 'Users';
    var $helpers = array('Session');
    var $components = array('Cookie', 'Captcha', 'Email');
    var $uses = array('User', 'Template', 'UserCredit');

    function beforeFilter() {
        parent::beforeFilter();
        // debug($this->Session);
        //debug($this->Auth);
        //die();
        $this->set('base_urll', 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'));
        $this->Auth->userScope = array('User.role =' => 'user');

        if (isset($this->params['admin']) && ($this->params['admin'] == '1')) {
            $this->Auth->userScope = array('User.role =' => 'admin');
            $this->Auth->userScope = array('User.status' => 1);
        }

        $this->Auth->autoRedirect = false;
        // echo $this->Session->setFlash("Welcome user");
        $this->Auth->allow('admin_login', 'check_email', 'register', 'check_login', 'ajax_register', 'refresh_captcha', 'confirm', 'successful', 'send_verification_again', 'fb_login');
        $this->Auth->loginRedirect = array('controller' => 'Dashboard', 'action' => 'index');
    }

    function admin_index() {
        if (!$this->Access->check('User', 'read')) {
            $this->Session->setFlash('You dont have permissions to View this content ');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }

        if (isset($this->params['named']['status'])) {
            $this->paginate = array(
                'limit' => '20',
                'conditions' => array('User.status =' => $this->params['named']['status'], 'User.role =' => 'user'),
                'order' => array('User.created' => 'desc')
            );
        } else {
            $this->paginate = array(
                'limit' => '1',
                'conditions' => array('User.role =' => 'user', 'User.status' => '1'),
                'order' => array('User.created' => 'desc')
            );
        }
        $data = $this->paginate('User');

        $this->set('users', $data);
    }

    function admin_register() {

        if (!empty($this->data)) {
            // Here you should validate the username (min length, max length, to not include special chars, not existing already, etc)  
            // As well as the password  
            $this->data['User']['role'] = 'admin';
            $this->data['User']['status'] = '1';
            /*             * ******************* Set Account type and created time ***************** */

            $this->data['UserProfile']['free_account_type'] = 'free';
            $this->data['UserProfile']['free_account_created'] = date('Y-m-d h:i:s');

            /*             * ************************************ */
            if ($this->User->save($this->data)) {
                $this->data['UserProfile']['user_id'] = $this->User->id;

                $this->User->UserProfile->save($this->data);
                // Let's read the data we just inserted  
                //$data = $this->User->read();
                // Use it to authenticate the user  
                //$this->Auth->login($data);
                $aro = new Aro();
                $parent = $aro->findByAlias($this->User->find('count') > 1 ? 'Moderator' : 'Super');

                $aro->create();
                $aro->save(array(
                    'model' => 'User',
                    'foreign_key' => $this->User->id,
                    'parent_id' => $parent['Aro']['id'],
                    'alias' => 'User::' . $this->User->id
                ));
                // Then redirect  
                $this->Session->setFlash('Moderator Created');
                $this->redirect(array('controller' => 'Users', 'action' => 'moderators'));
            }
        }
    }

    function admin_edit($id = null) {
        if (!$this->Access->check('User', 'update')) {
            $this->Session->setFlash('You dont have permissions to View this content ');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (empty($this->data)) {
            $tags = array();
            $this->data = $this->User->read(null, $id);
        } else {

            $this->User->id = $id;
            if (!empty($this->data['User']['pass'])) {
                $this->data['User']['password'] = $this->Auth->password($this->data['User']['pass']);
            }

            if ($this->User->save($this->data)) {
                $this->Session->setFlash("User updated");
                if ($this->data['User']['role'] == 'admin') {
                    $action = "moderators";
                } else {
                    $action = "index";
                };
                $this->redirect(array('controller' => 'Users', 'action' => $action, 'status' => '1'));
            }
        }
    }

    function admin_delete($id = null) {
        if (!$this->Access->check('User', 'delete')) {
            $this->Session->setFlash('You dont have permissions to View this content ');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        if (!$id) {
            $this->Session->setFlash("Invalid Link");
            $this->redirect(array('controller' => 'Users', 'action' => 'index'));
        }

        if ($this->User->delete($id)) {
            $delete = mysql_query("DELETE FROM `aros` where  `foreign_key`='$id'");
            if ($this->params['url']['type'] == 'user') {
                $this->redirect(array('controller' => 'Users', 'action' => 'index', 'status' => $this->params['url']['status']));
                $this->Session->setFlash("User deleted");
            } else {
                $this->Session->setFlash("Moderator deleted");
                $this->redirect(array('controller' => 'Users', 'action' => 'moderators'));
            }
        } else {
            $this->Session->setFlash('Moderator Not found.');
            if ($this->params['url']['type'] == 'user') {
                $this->redirect(array('controller' => 'Users', 'action' => 'index'));
            } else {
                $this->redirect(array('controller' => 'Users', 'action' => 'moderators'));
            }
        }
    }

    function admin_login() {
        if (isset($_SESSION['Auth']['admin']['User'])) {
            if (isset($_SESSION['Auth']['User']) || isset($_SESSION['Auth']['admin']['User']) || isset($_SESSION['Auth']['user']['User'])) {
                if (isset($this->params['admin'])) {

                    $_SESSION['Auth']['User'] = $_SESSION['Auth']['admin']['User'];
                } else {
                    $_SESSION['Auth']['User'] = $_SESSION['Auth']['user']['User'];
                }
            }
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        $this->set('title_for_layout', 'Rate The Universe - Admin Panel -Login');
        $this->layout = 'admin_login';
        if ($this->Auth->login()) {
            $_SESSION['Auth']['admin']['User'] = $_SESSION['Auth']['User'];

            $this->redirect($this->Auth->redirect());
        }
    }

    function admin_logout() {
        $this->set('title_for_layout', 'Rate The Universe - Admin Panel -Logout');
        session_destroy();
        session_unset();
        $this->redirect($this->Auth->logout());
    }

    function admin_set_permission() {
        if (!$this->Access->check('User')) {
            $this->Session->setFlash('You dont have permissions to View this content');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
    }

    function admin_moderators() {
        if (!$this->Access->check('User', 'read')) {
            $this->Session->setFlash('You dont have permissions to View this content ');
            $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
        }
        $this->paginate = array(
            'limit' => '10',
            'conditions' => array('User.id !=' => 1, 'User.role' => 'admin'),
            'order' => array('User.created' => 'desc')
        );
        $data = $this->paginate('User');

        $i = '0';
        foreach ($data as $user) {
            $data[$i]['UserCredit']['points'] = $this->get_points($user['User']['id']);
            $i++;
        }
        //$points=$this->get_points($id)();$this->sum_subarrays_by_key( $data['User']['UserCredit'], "credit" );
        $this->set('moderators', $data);
    }

    /*     * *************************************
     * We will sign in Admin to any user account using  this method.
     * It takes one argument  $id as user id.
     * ************* */

    function admin_sign_in($id) {
        if ($id) {
            $data = $this->User->find('first', array('conditions' => array('User.id =' => $id)));
            if ($data) {

                $_SESSION['Auth']['user']['User'] = $data['User'];
                $this->redirect(array('controller' => 'Homes', 'action' => '', 'admin' => false));
            }
        } else {
            $this->Session->setFlash('Insufficient data paased');
            $this->redirect(array('controller' => 'Users', 'action' => 'admin_index'));
        }
    }

    function register($data) {

        if (!empty($this->data)) {
            // Here you should validate the username (min length, max length, to not include special chars, not existing already, etc)  
            // As well as the password  
            //debug($this->RequestHandler->getClientIp());die();

            /*             * *************** This will be used when user is registered through facebook.  ****************** */
            $password = false;                                //Initialized to be used when user is registered through facebook.
            if (isset($this->data['fb_login'])) {
                $password = rand(10000, 99999);
                $this->data['User']['password'] = $this->Auth->password($password);
                $this->data['User']['status'] = '1';
            }
            /*             * *************** Facebook registration ends.  ****************** */
            $this->data['User']['email'] = $this->data['User']['username'];
            $this->data['User']['ip'] = $this->RequestHandler->getClientIp();
            $this->data['User']['role'] = 'user';
            /*             * ******************* Set Account type and created time ***************** */

            $this->data['UserProfile']['free_account_type'] = 'free';
            $this->data['UserProfile']['free_account_created'] = date('Y-m-d h:i:s');

            /*             * ************************************ */
            $this->User->set($this->data);
            if ($this->User->save($this->data)) {
                $this->data['UserProfile']['user_id'] = $this->User->id;
                $this->User->UserProfile->save($this->data);
                // Let's read the data we just inserted  
                //$data = $this->User->read();
                // Use it to authenticate the user  
                //$this->Auth->login($data);
                $aro = new Aro();
                $parent = $aro->findByAlias($this->User->find('count') > 1 ? 'User' : 'Moderator');

                $aro->create();
                $aro->save(array(
                    'model' => 'User',
                    'foreign_key' => $this->User->id,
                    'parent_id' => $parent['Aro']['id'],
                    'alias' => 'User::' . $this->User->id
                ));
                if ($password) {
                    $this->_sendpasswordtoUser($this->data['User']['username'], $password);
                }
                $email = $this->data['User']['username'];
                $this->data = '';
                $this->data['User']['username'] = $email;
                $this->data['User']['password'] = $this->Auth->password($password);
                // Then redirect  

                if ($this->Auth->login($this->data)) {

                    $_SESSION['Auth']['user']['User'] = $_SESSION['Auth']['User'];

                    $this->redirect(array('controller' => 'Homes', 'action' => 'index'));
                }
            }
        }
    }

    function index() {
        
    }

    function login() {
        
    }

    function logout() {
        $this->set('title_for_layout', 'Rate The Universe - Adminpanel -Logout');
        session_destroy();
        session_unset();
        $this->Auth->logout();

        $this->redirect(array('controller' => 'homes', 'action' => 'index'));
    }

    function check_email() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            if (isset($_POST['email'])) {

                $query = mysql_query("SELECT username from user where username='" . $_POST['email'] . "' || (`email`='" . $_POST['email'] . "' && role='admin')") or die(mysql_error());

                if (mysql_num_rows($query) > 0) {

                    echo "Email taken. Choose another";
                }
            }
        }
    }

    function check_login() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $error = true;

            if (isset($_POST['username'])) {
                $this->data['User']['username'] = $_POST['username'];
                $this->data['User']['password'] = $this->Auth->password($_POST['password']);

//                $query = mysql_query("SELECT username from user where (username='" . $this->data['User']['username'] . "' && password ='" . $this->data['User']['password'] . "') || (`email`='" . $this->data['User']['username'] . "' && password ='" . $this->data['User']['password'] . "' && role='admin')"); // Cuastom query to let admin login at front end with their username or email
                $query = mysql_query("SELECT username from user where (username='" . $this->data['User']['username'] . "' && password ='" . $this->data['User']['password'] . "') || (`email`='" . $this->data['User']['username'] . "' && password ='" . $this->data['User']['password'] . "')"); // Cuastom query to let admin/user login at front end with their username or email

                if (mysql_num_rows($query) == '1') {
                    //$data = $this->User->find('all', array('conditions' => array('User.username =' => $this->data['User']['username'], 'User.password =' => $this->data['User']['password'])));

                    $this->Auth->userScope = array('User.status' => '1');
                    if ($this->Auth->login($this->data)) {

                        $_SESSION['Auth']['user']['User'] = $_SESSION['Auth']['User'];

                        if ($_POST['remember'] == '1') {

                            $this->Cookie->write('User', array('User.username' => $this->data['User']['username'], 'User.password' => $this->data['User']['password']), true, '4 weeks');
                        }
                        $response['error'] = false;
                        $error = false;
                    } else if (!$this->Auth->User('id')) {
                        $this->Auth->fields = array('username' => 'email', 'password' => 'password');
                        $this->data['User']['email'] = $this->data['User']['username'];

                        if ($this->Auth->login($this->data)) {

                            $_SESSION['Auth']['user']['User'] = $_SESSION['Auth']['User'];

                            if ($_POST['remember'] == '1') {

                                $this->Cookie->write('User', array('User.username' => $this->data['User']['email'], 'User.password' => $this->data['User']['password']), true, '4 weeks');
                            }
                            $response['error'] = false;
                            $error = false;
                        }
                    }
                    if ($error) {
                        $response['error'] = true;
                        $response['type'] = '1';
                        $response['desc'] = 'Not verified';
                        $response['email'] = $this->data['User']['username'];
                    }
                }

                if ($error) {
                    $response['error'] = true;
                    $response['type'] = '2';
                    $response['desc'] = 'Username/password do not match';
                }
            }
            $resp = json_encode($response);
            echo $resp;
        }
    }

    function send_verification_again() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();

            if (isset($_POST['email'])) {
                $data = $this->User->find('first', array('conditions' => array('User.username' => $_POST['email'], 'User.status' => '0')));
                if ($data) {
                    $uid = $this->_sendNewUserMail($_POST['email']);
                    if ($uid) {
                        $query = mysql_query("UPDATE `user` set `confirmation_id`='$uid' WHERE `id`='" . $data['User']['id'] . "'");
                        if ($query) {
                            $response['error'] = false;
                        } else {
                            $response['error'] = true;
                            $response['desc'] = "Email not sent. Try again later";
                        }
                    }
                } else {
                    $response['error'] = true;
                    $response['desc'] = "Email address you provided doesn't matches with our database. Please check your email address";
                }
                $response = json_encode($response);
                echo $response;
            }
        }
    }

    function ajax_register() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;

            if (isset($_POST['captcha'])) {
                if ($_POST['captcha'] == $_SESSION['ver_code']) {
                    if (isset($_POST['email'])) {
                        $query = mysql_query("SELECT username from user where username='" . $_POST['email'] . "' || (`email`='" . $_POST['email'] . "' && role='admin')");

                        if (mysql_num_rows($query) > 0) {
                            echo "Email taken. Choose another";
                        } else {
                            $data = $this->User->find('first', array('or' => array('User.username' => $_POST['email'], '')));
                            $this->data['User']['username'] = $_POST['email'];
                            $this->data['User']['password'] = Security::hash($_POST['pass'], null, true);
                            $this->data['User']['email'] = $this->data['User']['username'];
                            $this->data['User']['ip'] = $this->RequestHandler->getClientIp();
                            $this->data['User']['role'] = 'user';

                            /*                             * ******************* Set Account type and created time ***************** */

                            $this->data['UserProfile']['free_account_type'] = 'free';
                            $this->data['UserProfile']['free_account_created'] = date('Y-m-d h:i:s');

                            /*                             * ************************************ */
                            $this->User->set($this->data);
                            $uid = $this->_sendNewUserMail($this->data['User']['email']);
                            $this->data['User']['confirmation_id'] = $uid;
                            if ($uid) {
                                if ($this->User->saveAll($this->data)) {
                                    //$this->data['UserProfile']['user_id']=$this->User->id;
                                    //$this->User->UserProfile->save($this->data);
                                    // Let's read the data we just inserted  
                                    //$data = $this->User->read();
                                    // Use it to authenticate the user  
                                    //$this->Auth->login($data);

                                    $aro = new Aro();
                                    $parent = $aro->findByAlias($this->User->find('count') > 1 ? 'User' : 'Moderator');

                                    $aro->create();
                                    $aro->save(array(
                                        'model' => 'User',
                                        'foreign_key' => $this->User->id,
                                        'parent_id' => $parent['Aro']['id'],
                                        'alias' => 'User::' . $this->User->id
                                    ));
                                    // Then redirect 
//$this->Session->setFlash('Thank you for registering. Please check your email to confirm.');
                                } else {
                                    echo "Something went wrong. Please try again later";
                                }
                            } else {
                                echo "Something went wrong. Please try again later";
                            }
                        }
                    } else {
                        echo "Enter Email";
                    }
                } else {
                    echo "Security code do not match";
                }
            }
        }
    }

    function confirm($confirmation_id = null) {

        $data = $this->User->find('first', array('conditions' => array('User.confirmation_id =' => $confirmation_id)));

        if ($data) {
            $this->User->id = $data['User']['id'];
            $this->data['User']['confirmation_id'] = '';
            $this->data['User']['status'] = '1';
            $this->User->save($this->data);

            if ($this->Auth->login($data)) {
                $_SESSION['Auth']['user']['User'] = $_SESSION['Auth']['User'];
                $this->_sendRegistrationMail($data['User']['email']);
                $this->Session->setFlash('Welcome User. Thanks for Registring To Rate The Universe.');
                $this->redirect(array('controller' => 'Profiles', 'action' => 'profile'));
            }
        } else {
            $this->Session->setFlash('Invalid token passed.');
            $this->redirect(array('controller' => 'Homes', 'action' => 'index'));
        }
    }

    function successful() {
        $this->set('User', $this->Auth->user());
    }

    function refresh_captcha() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->layout = '';
            App::import("Component", "Captcha"); //including captcha class
            $this->Captcha = new CaptchaComponent(); //creating an object instance
            $this->Captcha->controller = & $this; //assign this conroller(CaptchaController) object to its captcha object's controller property.
            $captcha_src = $this->Captcha->create();
            $this->set('captcha_src', $captcha_src = $this->Captcha->create()); //create a capthca and assign to a variable
        }
    }

    function _send_mail($from, $to, $data, $template) {
        $this->Email->from = $from;
        $this->Email->to = $to;
        $this->Email->subject = $data['subject'];
        $this->Email->template = $template;
        //Send as 'html', 'text' or 'both' (default is 'text')
        $this->Email->sendAs = 'both'; // because we like to send pretty mail
        $email_element = $data['email_element'];// => $email_element['email_template'] == $db_template['Template'];        
        $this->set('email_element', $email_element);        
        $result = $this->Email->send();
        return $result;        
    }

    function sendVerificationMail($from,$to,$confirm_link) {
        $template = 'verification_email';
        $data['subject'] = 'Verify Your Account';
        $data['email_element']['confirm_link'] = $confirm_link;
        $db_template = $this->Template->find('first', array('conditions' => array('Template.alias =' => 'NewUserMail')));        
        $data['email_element']['email_template'] = $db_template['Template'];        
        $result = $this->_send_mail($from, $to, $data, $template);
        return $result;
    }

    function test_send_mail() {
        /* $this->Email->from    = 'khanv.it@gmail.com';
          $this->Email->to      = 'khanv.it@gmail.com';
          $this->Email->subject = 'Test';
          $this->Email->template = 'verification_email';
          $User['User']['first'] = 'Kha';
          $User['User']['last'] = 'Nguyen';
          $this->set('User', $User);
          $r = $this->Email->send();
          var_dump($r);die(); */

        /*
        $from = 'khanv.it@gmail.com';
        $to = 'khanv.it@gmail.com';
        $template = 'test_email';
        $data['subject'] = 'Verify Your Account';
        $data['email_element']['first_name'] = 'Kha';
        $data['email_element']['last_name'] = 'Nguyen';
        $result = $this->_send_mail($from, $to, $data, $template);
        var_dump($result);
        die();
        */
        
//        $result = $this->sendVerificationMail('khanv.it@gmail.com','khanv.it@gmail.com','www.google.com');
        $result = $this->_sendNewUserMail('khanv.it@gmail.com');
        var_dump($result);die();
    }
    
    function _sendNewUserMail($email) {
        $this->set('base_url', 'http://ratetheu.com/com/hung');
        $this->Email->to = $email;
        $template = $this->Template->find('first', array('conditions' => array('Template.alias =' => 'NewUserMail')));
        $this->Email->subject = $template['Template']['title'];
        //$this->Email->replyTo = 'info@ratetheu.com';
        $this->Email->from = 'Rate The Universe <support@primeag.org>';
        $this->Email->template = 'email'; // note no '.ctp'
        $this->Email->sendAs = 'both'; // because we like to send pretty mail
//        if ($_SERVER['HTTP_HOST']) {
//            $this->Email->delivery = 'debug';
//        }

//$this->Email->delivery = 'debug';
        //delivery type is set to debug
        $this->set('template', $template);
        $User['uid'] = uniqid('RTU', true);
        $User['email'] = $email;
        $this->set('user', $User);
//Do not pass any args to send()
        if ($this->Email->send()) {
            return $User['uid'];
        } else {
            return false;
        }
    }

    function _sendRegistrationMail($email) {
        $this->Email->to = $email;
        $template = $this->Template->find('first', array('conditions' => array('Template.alias =' => 'Registration')));
        $this->Email->subject = $template['Template']['title'];
        //$this->Email->replyTo = 'info@ratetheu.com';
        $this->Email->from = "Rate The Universe<support@primeag.org>";
        $this->Email->template = 'email'; // note no '.ctp'
        $this->Email->sendAs = 'both'; // because we like to send pretty mail
//        if ($_SERVER['HTTP_HOST']) {
//            $this->Email->delivery = 'debug';
//        }
//        
//        $this->Email->delivery = 'debug';
        //delivery type is set to debug
        $this->set('template', $template);
        $User['uid'] = null;
        $User['email'] = $email;
        $this->set('user', $User);
//Do not pass any args to send()

        if ($this->Email->send()) {
            return true;
        } else {
            return false;
        }
    }

    function _sendpasswordtoUser($email, $password) {
        $this->Email->to = $email;
        $template = $this->Template->find('first', array('conditions' => array('Template.alias =' => 'fbRegistration')));
        $this->Email->subject = $template['Template']['title'];
        //$this->Email->replyTo = 'info@ratetheu.com';
        $this->Email->from = "Rate The Universe<support@primeag.org>";
        $this->Email->template = 'email'; // note no '.ctp'
        $this->Email->sendAs = 'both'; // because we like to send pretty mail

//        if ($_SERVER['HTTP_HOST']) {
//            $this->Email->delivery = 'debug';
//        }
        
        //$this->Email->delivery = 'debug';
        //delivery type is set to debug
        $this->set('template', $template);
        $User['uid'] = null;
        $User['email'] = $email;
        $User['password'] = $password;
        $this->set('user', $User);
//Do not pass any args to send()

        if ($this->Email->send()) {
            return true;
        } else {
            return false;
        }
    }

    function fb_login() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            if (isset($_POST['mail'])) {

                $data = $this->User->find('all', array('conditions' => array('User.username' => $_POST['mail'])));

                if (count($data) == '1') {

                    $this->data['User']['username'] = $data['0']['User']['username'];
                    $this->data['User']['password'] = $data['0']['User']['password'];
                    if ($this->Auth->login($this->data)) {
                        $_SESSION['Auth']['user']['User'] = $_SESSION['Auth']['User'];
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    $this->data['User']['username'] = $_POST['mail'];
                    $this->data['fb_login'] = true;
                    $this->register($this->data);
                }
            }
        }
    }

}

?>